/* eslint-disable eqeqeq */
// app/service/user.js
const Service = require('egg').Service;

class IoService extends Service {
  async sendmessage(type = 'message', id, msg) {
    const { ctx, app } = this;
    const token = ctx.request.header.authorization;
    const decode = await app.jwt.verify(token, app.config.jwt.secret);
    const other_id = decode.id;
    const otherinfo = await ctx.model.User.findByPk(decode.id);
    // 当前登录人 与 推送人一样
    if (other_id == id && type === 'message') {
      return {};
    }
    const resmsg = {
      ...msg,
      other_id,
      otherinfo,
    };

    // 创建消息提醒信息 后推送;
    let notice,
      err;
    if (Array.isArray(id)) {
      const mutiadder = id
        ?.filter(it => it !== other_id)
        ?.map(it => ({
          ...resmsg,
          userid: it,
        }));
      try {
        notice = await ctx?.model?.Notice?.bulkCreate(mutiadder);
      } catch (error) {
        err = error;
        notice = 'error';
      }
    } else {
      try {
        notice = await ctx?.model?.Notice?.create(resmsg);
      } catch (error) {
        err = error;
        notice = 'error';
      }
    }

    if (notice === 'error') {
      return err;
    }

    const clients = app.io.sockets.sockets;
    // query中的id为 用户id  io可以直接emit
    Object.values(clients)?.map(io => {
      if (Array.isArray(notice)) {
        const msgs = notice?.map(it => it?.dataValues);
        const index = msgs
          ?.map(it => it?.userid)
          .indexOf(parseInt(io?.handshake?.query?.id));
        if (index !== -1) {
          io.emit(type, msgs[index]);
        }
      } else if (io?.handshake?.query?.id == id) {
        io.emit(type, notice?.dataValues);
      }
      return io;
    });

    return notice;
  }
}

module.exports = IoService;
